package com.briup.product_source.web.controller;

import com.briup.product_source.config.UploadProperties;
import com.briup.product_source.util.OSSUtil;
import com.briup.product_source.util.Result;
import com.briup.product_source.util.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Api(tags ="文件上传")
@RestController
@Slf4j
public class FileController {
    @Autowired
    private OSSUtil ossUtil;
    @Autowired
    private UploadProperties uploadProp;
    @ApiOperation("文件上传接口,储存到七牛云空间")
    @PostMapping("/file/upload")
    public String upload(@RequestPart MultipartFile file) throws IOException {
        String id = UUID.randomUUID().toString().replace("-","");
        String newFileName = id + file.getOriginalFilename();
        ossUtil.upload(newFileName,file.getInputStream());
        return newFileName;
    }

    @ApiOperation("将文件储存到指定路径")
    @PostMapping("/upload")
    public String uploads(@RequestPart MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        long size = file.getSize();
        log.info("文件名：{},文件大小：{}",filename,size);
        byte[] bytes = file.getBytes();
        InputStream in = file.getInputStream();
        String id = UUID.randomUUID().toString();
        String newFileName = id + filename;
        log.info("文件保存目录："+uploadProp.getDir());
        file.transferTo(new File(uploadProp.getDir(),newFileName));
        return uploadProp.baseUrl()+newFileName;
    }
}
